import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import BigNumber from 'bignumber.js'

export const message = function (msg, type) {
  ElMessage({
    showClose: true,
    message: msg || '消息',
    type: type || 'success',
    duration: type === 'error' ? 5000 : 3000,
  })
}
export const notify = function (msg, type) {
  ElNotification({
    title: '提示',
    message: msg || '消息',
    type: type || 'success',
  })
}
export const confirm = function (text) {
  return ElMessageBox.confirm(text, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
}

/**
 * 列单元格合并
 * @param tableData table列表数据
 * @param mergeName 要合并的字段 ['name','age']
 * { row, column, rowIndex, columnIndex } // el-table :span-method方法 回调参数
 */
export const mergeColumnMethod = function (tableData = [], mergeName = [], { row, column, rowIndex, columnIndex }) {
  let spanArr = []
  let contactDotb = 0
  if (mergeName.includes(column.property)) {
    tableData.forEach((item, index) => {
      if (index === 0) {
        spanArr.push(1)
      } else {
        if (item[column.property] != null && item[column.property] === tableData[index - 1][column.property]) {
          spanArr[contactDotb] += 1
          spanArr.push(0)
        } else {
          contactDotb = index
          spanArr.push(1)
        }
      }
    })
    return {
      rowspan: spanArr[rowIndex],
      colspan: spanArr[rowIndex] > 0 ? 1 : 0,
    }
  }
}

/**
 * 表格合计
 * @param { columns, data } :summary-method 回调参数
 * @param columnKeys 要合计列的key ['amountTotal','number']
 * @param sumKey  要在那列展示 '总计' 默认第一个
 * @param sumText 显示摘要行第一列的文本 默认总计
 */

export const sumTotalMethod = ({ columns, data }, columnKeys = [], sumKey, sumText) => {
  const sums = []
  columns.forEach((item, index) => {
    if ((!sumKey && index == 0) || item.property == sumKey) {
      sums[index] = sumText ? sumText : '总计'
      return
    }
    //columnKeys 如果是空的默认计算所有column
    if (!columnKeys.length) columnKeys = columns.map((i) => i.property)

    if (columnKeys.includes(item.property)) {
      sums[index] = data.reduce((pre, curr) => {
        const value = Number(curr[item.property])
        if (!Number.isNaN(value)) {
          return BigNumber(pre).plus(value).toNumber()
        } else {
          return pre
        }
      }, 0)
    } else {
      sums[index] = null
    }
  })
  return sums
}
